<?php
declare (strict_types=1);

namespace app\admin\service;

use app\admin\model\huiP2Order\PartnerUserModel;
use app\common\enum\sms\SceneEnum;
use app\common\service\SmsCaptchaService;
use think\facade\Cache;

class AuthService extends AdminBaseService
{
    // 用于生成token的自定义盐
    const TOKEN_SALT = '_admin_user_salt_';

    // 短信验证码登录
    public function loginBySmsCode(array $data): array
    {
        // 数据验证
        $rule = [
            'mobile' => 'require|mobile',
            'sms_code' => 'require',
        ];
        validate($rule)->check($data);

        // 验证短信验证码
        $check_res = SmsCaptchaService::checkSms($data['sms_code'], $data['mobile'], SceneEnum::LOGIN);
        if (!$check_res['code']) return $check_res;

        // 查询用户
        $user_info = PartnerUserModel::where('phone', $data['mobile'])->find();
        if (!$user_info) return render_array_error('手机号不存在');
        if (!in_array($user_info, [10, 12])) return render_array_error('仅支持服务商和BD账号登录');

        return render_array_success($this->loginSuccess($user_info->toArray()), '登录成功');
    }

    public function loginSuccess(array $user_info): array
    {
        $token = self::generateToken((int)$user_info['user_id']);

        // 记录缓存, 7天
        Cache::set($token, [
            'user' => [
                'user_id' => (int)$user_info['admin_user_id'],
                'nick_name' => $user_info['nick_name'],
            ],
            'is_login' => true,
        ], 86400 * 7);

        return [
            'token' => $token
        ];
    }

    // 退出登录
    public function logout()
    {
        Cache::delete(self::getToken());
        return true;
    }

    // 获取登录的信息
    public static function getLoginInfo()
    {
        if (($token = self::getToken()) !== false) {
            return Cache::get($token);
        }
        return false;
    }

    // 判断是否登录
    public static function isLogin()
    {
        if (($token = self::getToken()) !== false) {
            return Cache::get($token)['user']['user_id'];
        }
        return false;
    }

    // 生成用户认证的token
    private static function generateToken(int $user_id): string
    {
        // 生成一个不会重复的随机字符串
        $guid = get_guid_v4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = self::TOKEN_SALT;
        return md5("{$timeStamp}_{$user_id}_{$guid}_{$salt}");
    }

    // 获取用户认证Token
    private static function getToken()
    {
        // 获取请求中的token
        $token = request()->header('Access-Token');
        // 调试模式下可通过param
        if (empty($token) && is_debug()) {
            $token = request()->param('Access-Token');
        }
        // 不存在token报错
        if (empty($token)) {
            return false;
        }
        return $token;
    }


}
